import globalWSManager from './global-manager.js'

/**
 * 统一的 WebSocket 管理器
 */
export class WebSocketManager {
  constructor(options = {}) {
    this.ws = null
    this.url = options.url || ''
    this.onMessage = options.onMessage || (() => {})
    this.onOpen = options.onOpen || (() => {})
    this.onClose = options.onClose || (() => {})
    this.onError = options.onError || (() => {})
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = options.maxReconnectAttempts || 3
    this.reconnectInterval = options.reconnectInterval || 3000
    this.autoReconnect = options.autoReconnect !== false
    this.isConnected = false
    this.isConnecting = false
    this.connectionId = null
    this.preventReconnect = false // 新增：防止重连标志
    this.connectionType = options.connectionType || 'unknown'
    this.roomId = options.roomId || ''
    this.gameType = options.gameType || ''
  }

  /**
   * 连接 WebSocket
   */
  connect() {
    return new Promise((resolve, reject) => {
      // 检查是否已有相同类型的连接
      if (globalWSManager.hasConnection(this.connectionType, this.roomId, this.gameType)) {
        const existingManager = globalWSManager.getConnection(this.connectionType, this.roomId, this.gameType)
        console.log(`已存在相同类型的连接: ${this.connectionType}`, existingManager)
        
        // 如果现有连接已连接，直接返回
        if (existingManager && existingManager.getConnected()) {
          console.log('使用现有连接')
          // 复制现有连接的状态
          this.ws = existingManager.ws
          this.isConnected = existingManager.isConnected
          this.isConnecting = existingManager.isConnecting
          this.connectionId = existingManager.connectionId
          
          // 设置消息处理器
          if (this.ws) {
            this.ws.onmessage = (event) => {
              try {
                if (!event.data || event.data.trim() === '') {
                  console.warn('收到空的WebSocket消息，跳过处理');
                  return;
                }
                
                const message = JSON.parse(event.data)
                this.onMessage(message)
              } catch (error) {
                console.error('解析WebSocket消息失败:', error, '原始数据:', event.data)
              }
            }
          }
          
          resolve()
          return
        }
      }

      // 如果正在连接或已连接，直接返回
      if (this.isConnecting || this.isConnected) {
        console.log('WebSocket已连接或正在连接中，跳过重复连接')
        resolve()
        return
      }

      try {
        this.isConnecting = true
        this.connectionId = Date.now()
        
        console.log('开始连接WebSocket:', this.url)
        console.log('当前环境:', typeof window !== 'undefined' ? '浏览器' : 'APP')
        console.log('WebSocket对象:', typeof WebSocket)
        
        // 添加连接超时
        const connectionTimeout = setTimeout(() => {
          console.error('WebSocket连接超时')
          this.isConnecting = false
          this.onError(new Error('连接超时'))
          reject(new Error('连接超时'))
        }, 10000) // 10秒超时
        
        // 检查是否在uni-app环境中
        if (typeof uni !== 'undefined' && uni.connectSocket) {
          // 在uni-app环境中，使用原生WebSocket而不是uni.connectSocket
          console.log('检测到uni-app环境，使用原生WebSocket')
        }
        
        // 使用原生WebSocket（在所有环境中）
        this.ws = new WebSocket(this.url)
        
        this.ws.onopen = () => {
          console.log('WebSocket连接成功')
          clearTimeout(connectionTimeout)
          this.isConnected = true
          this.isConnecting = false
          
          // 注册到全局管理器
          globalWSManager.registerConnection(this.connectionType, this.roomId, this.gameType, this)
          globalWSManager.updateConnectionState(this.connectionType, this.roomId, this.gameType, {
            isConnected: true,
            isConnecting: false
          })
          
          this.onOpen()
          resolve()
        }
        
        this.ws.onmessage = (event) => {
          try {
            // 检查数据是否为空
            if (!event.data || event.data.trim() === '') {
              console.warn('收到空的WebSocket消息，跳过处理');
              return;
            }
            
            const message = JSON.parse(event.data)
            this.onMessage(message)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error, '原始数据:', event.data)
          }
        }
        
        this.ws.onclose = (event) => {
          console.log('WebSocket连接关闭:', event.code, event.reason)
          clearTimeout(connectionTimeout)
          this.isConnected = false
          this.isConnecting = false
          
          // 更新全局管理器状态
          globalWSManager.updateConnectionState(this.connectionType, this.roomId, this.gameType, {
            isConnected: false,
            isConnecting: false
          })
          
          this.onClose(event)
          
          // 只有在正常关闭且未设置防止重连标志时才自动重连
          if (this.autoReconnect && !this.preventReconnect && this.reconnectAttempts < this.maxReconnectAttempts && 
              (event.code === 1000 || event.code === 1001)) {
            this.reconnectAttempts++
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
            setTimeout(() => {
              this.connect()
            }, this.reconnectInterval)
          }
        }
        
        this.ws.onerror = (error) => {
          console.error('WebSocket连接错误:', error)
          clearTimeout(connectionTimeout)
          this.isConnected = false
          this.isConnecting = false
          this.onError(error)
          reject(error)
        }

      } catch (error) {
        console.error('创建WebSocket连接失败:', error)
        this.isConnecting = false
        reject(error)
      }
    })
  }

  /**
   * 发送消息
   */
  send(message) {
    if (!this.isConnected || !this.ws) {
      console.warn('WebSocket未连接，无法发送消息')
      return false
    }

    try {
      const data = typeof message === 'string' ? message : JSON.stringify(message)
      this.ws.send(data)
      console.log('消息发送成功:', message)
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      this.onError(error)
      return false
    }
  }

  /**
   * 关闭连接
   */
  close() {
    console.log('关闭WebSocket连接')
    
    // 设置防止重连标志，防止用户离开后自动重连
    this.preventReconnect = true
    
    // 重置连接状态
    this.isConnected = false
    this.isConnecting = false
    this.connectionId = null
    
    // 从全局管理器中注销
    globalWSManager.unregisterConnection(this.connectionType, this.roomId, this.gameType)
    
    if (this.ws) {
      try {
        // 发送关闭消息
        if (this.ws.readyState === WebSocket.OPEN) {
          this.ws.close(1000, '用户主动离开')
        } else {
          this.ws.close()
        }
        console.log('WebSocket连接已关闭')
      } catch (error) {
        console.error('关闭WebSocket连接失败:', error)
      }
      this.ws = null
    }
  }

  /**
   * 检查连接状态
   */
  getConnected() {
    return this.isConnected
  }

  /**
   * 检查是否正在连接
   */
  getConnecting() {
    return this.isConnecting
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      isConnecting: this.isConnecting,
      connectionId: this.connectionId
    }
  }

  /**
   * 重置防止重连标志
   */
  resetPreventReconnect() {
    this.preventReconnect = false
  }
}

/**
 * 安全关闭 WebSocket 连接
 */
export function safeCloseWebSocket(manager) {
  if (manager && typeof manager.close === 'function') {
    try {
      manager.close()
    } catch (error) {
      console.error('关闭WebSocket连接失败:', error)
    }
  }
}

/**
 * 创建 WebSocket 消息
 */
export function createMessage(type, data = {}, options = {}) {
  const message = {
    type: type,
    time: Math.floor(Date.now() / 1000),
    ...data,
    ...options
  }
  
  return message
} 